package com.example.qt.ptplatform.network;

import java.net.URLEncoder;
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.OutputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.util.List;
import java.util.Map;

import com.example.qt.ptplatform.mapper.TorrentMapper;
import com.example.qt.ptplatform.entity.Torrent;
import com.example.qt.ptplatform.entity.TorrentMapping;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ClientUploader {

    private static final String QB_API_URL = "http://localhost:8000/api/v2";
    private static final int MAX_RETRIES = 3;
    private static final int RETRY_DELAY_MS = 2000;
    private String authCookie = null;

    @Autowired
    private TorrentMapper torrentMapper;

    // 登录并获取上传和下载的统计数据
    public boolean updateUploadAndDownloadCount(Integer userId, String qbUsername, String qbPassword) {
        try {
            // 登录到 qBittorrent
            if (!loginToQbittorrent(qbUsername, qbPassword)) {
                System.out.println("qBittorrent登录失败");
                return false;
            }

            // 获取上传和下载统计数据
            JSONObject stats = getUploadAndDownloadStats();
            if (stats != null) {
                float uploadCountChange = (float) stats.getDouble("uploaded");
                float downloadCountChange = (float) stats.getDouble("downloaded");

                // 将获取的上传和下载量更新到数据库
                return sendDataToPtPlatform(userId, uploadCountChange, downloadCountChange);
            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    // 登录 qBittorrent，获取登录凭证
    private boolean loginToQbittorrent(String username, String password) {
        try {
            URL url = new URL(QB_API_URL + "/auth/login");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("User-Agent", "Mozilla/5.0");
            connection.setDoOutput(true);

            // 使用URLEncoder进行编码
            String postData = "username=" + URLEncoder.encode(username, "UTF-8")
                    + "&password=" + URLEncoder.encode(password, "UTF-8");

            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = postData.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            int responseCode = connection.getResponseCode();
            System.out.println("登录响应码: " + responseCode);

            // 读取响应内容
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String responseBody = reader.readLine();
            reader.close();
            System.out.println("登录响应体: " + responseBody);

            if (responseCode == HttpURLConnection.HTTP_OK && "Ok.".equals(responseBody)) {
                // 获取Cookie
                Map<String, List<String>> headers = connection.getHeaderFields();
                for (String key : headers.keySet()) {
                    if (key != null && key.equalsIgnoreCase("Set-Cookie")) {
                        List<String> cookies = headers.get(key);
                        for (String cookie : cookies) {
                            if (cookie.startsWith("SID=")) {
                                authCookie = cookie.split(";")[0];
                                System.out.println("成功获取Cookie: " + authCookie);
                                return true;
                            }
                        }
                    }
                }
                System.out.println("登录成功但未找到Cookie");
                return false;
            } else {
                System.out.println("登录失败，响应体: " + responseBody);
                return false;
            }
        } catch (Exception e) {
            System.out.println("登录异常: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    // 获取 qBittorrent 中的上传和下载数据
    private JSONObject getUploadAndDownloadStats() {
        if (authCookie == null) {
            System.out.println("未找到有效Cookie，请先登录");
            return null;
        }

        int attempts = 0;
        while (attempts < MAX_RETRIES) {
            HttpURLConnection connection = null;
            try {
                URL url = new URL(QB_API_URL + "/torrents/info");
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.setRequestProperty("Cookie", authCookie);
                connection.setRequestProperty("User-Agent", "Mozilla/5.0");
                connection.setRequestProperty("Accept", "application/json");
                connection.setConnectTimeout(5000);
                connection.setReadTimeout(5000);

                int responseCode = connection.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    reader.close();

                    JSONArray torrents = new JSONArray(response.toString());
                    if (torrents.length() == 0) {
                        System.out.println("未找到种子数据");
                        return null;
                    }

                    double totalUploaded = 0;
                    double totalDownloaded = 0;
                    for (int i = 0; i < torrents.length(); i++) {
                        JSONObject torrent = torrents.getJSONObject(i);
                        totalUploaded += torrent.getDouble("uploaded");
                        totalDownloaded += torrent.getDouble("downloaded");

                        String qbittorrentHash = torrent.getString("hash");
                        // 查找对应的 torrentId
                        TorrentMapping mapping = torrentMapper.findByQbittorrentHash(qbittorrentHash);
                        if (mapping != null) {
                            // 更新数据库中的 torrent 信息
                            Torrent dbTorrent = torrentMapper.selectById(mapping.getTorrentId());
                            dbTorrent.setSizeGB(torrent.getDouble("size"));
                            dbTorrent.setRealFilename(torrent.getString("filename"));
                            dbTorrent.setIsPromo(torrent.getBoolean("isSeeding"));
                            torrentMapper.updateById(dbTorrent);
                        }
                    }

                    JSONObject stats = new JSONObject();
                    stats.put("uploaded", totalUploaded);
                    stats.put("downloaded", totalDownloaded);
                    return stats;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            attempts++;
            try {
                Thread.sleep(RETRY_DELAY_MS);
            } catch (InterruptedException ie) {
                Thread.currentThread().interrupt();
            }
        }
        return null;
    }

    // 更新上传和下载量到 PT 站
    private boolean sendDataToPtPlatform(int userId, float uploadCountChange, float downloadCountChange) {
        try {
            URL url = new URL("http://localhost:8080/user/updateCounts");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setDoOutput(true);

            String postData = "user_id=" + userId
                    + "&upload_count=" + uploadCountChange
                    + "&download_count=" + downloadCountChange;

            try (OutputStream os = conn.getOutputStream()) {
                byte[] input = postData.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            int responseCode = conn.getResponseCode();
            return responseCode == HttpURLConnection.HTTP_OK;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    // 种子状态更新方法，前端只需传递 qbUsername 和 qbPassword，后端自动获取状态
    public boolean updateTorrentSeedStatus(Integer userId, Integer torrentId, String qbUsername, String qbPassword) {
        try {
            // 从数据库中获取 torrent 信息
            Torrent torrent = torrentMapper.selectById(torrentId);
            if (torrent == null) {
                System.out.println("未找到该种子信息");
                return false;
            }

            // 登录并获取种子信息
            if (!loginToQbittorrent(qbUsername, qbPassword)) {
                System.out.println("qBittorrent登录失败");
                return false;
            }

            JSONObject stats = getUploadAndDownloadStats();
            if (stats == null) {
                System.out.println("未能获取到种子状态");
                return false;
            }

            // 获取种子的状态、大小、文件名等
            double sizeGB = torrent.getSizeGB();
            String realFilename = torrent.getRealFilename();

            // 更新种子状态
            torrent.setSizeGB(sizeGB);
            torrent.setRealFilename(realFilename);
            torrent.setIsPromo(torrent.getIsPromo());

            // 保存更新后的种子信息
            int result = torrentMapper.updateById(torrent);
            return result > 0;

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
